<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\DB;
use ReflectionClass;

class GeneratePermissions extends Command
{
    protected $signature = 'permission:generate';
    protected $description = '根据路由生成后台权限';

    /**
     * 执行命令
     */
    public function handle(): void
    {
        $routeFile = base_path('routes/admin.php');
        if (!File::exists($routeFile)) {
            $this->error('路由文件不存在：' . $routeFile);
            return;
        }

        $routes = $this->parseRouteFile($routeFile);
        if (empty($routes)) {
            $this->warn('未找到需要生成权限的路由');
            return;
        }

        foreach ($routes as $route) {
            $this->generatePermission($route);
        }

        $this->info('权限生成完成！');
    }

    /**
     * 解析路由文件
     */
    protected function parseRouteFile(string $filePath): array
    {
        $lines = file($filePath);
        $routes = [];
        $inPermissionGroup = false;

        foreach ($lines as $line) {
            $line = trim($line);

            // 检查是否进入权限中间件组
            if (strpos($line, "'middleware'") !== false &&
                (strpos($line, "'permission'") !== false)) {
                $inPermissionGroup = true;
                continue;
            }

            // 检查是否离开路由组
            if ($inPermissionGroup && $line === '});') {
                $inPermissionGroup = false;
                continue;
            }

            // 如果在权限组内，解析路由
            if ($inPermissionGroup && !empty($line)) {
                // 匹配路由定义
                if (preg_match('/\$router->(get|post|put|delete|patch)\s*\(\s*[\'"]([^\'"]*)[\'"]\s*,\s*[\'"]([^\'"]*)[\'"]\s*\)/', $line, $matches)) {
                    $routes[] = [
                        'method' => strtolower($matches[1]),
                        'path' => $matches[2],
                        'action' => $matches[3]
                    ];
                }
            }
        }

        $this->info('总共找到路由数量: ' . count($routes));
        return $routes;
    }

    /**
     * 生成权限
     */
    protected function generatePermission(array $route): void
    {
        [$controller, $method] = explode('@', $route['action']);
        $controller = str_replace('Admin\\', '', $controller);
        $module = strtolower(str_replace('Controller', '', $controller));

        // 获取控制器类
        $fullClassName = "App\\Http\\Controllers\\Admin\\{$controller}";
        if (!class_exists($fullClassName)) {
            $this->warn("控制器不存在：{$controller}");
            return;
        }

        // 获取方法的注解信息
        $reflection = new ReflectionClass($fullClassName);
        if (!$reflection->hasMethod($method)) {
            $this->warn("方法不存在：{$controller}@{$method}");
            return;
        }

        $name = $this->generatePermissionName($method);

        // 检查权限是否存在
        $exists = DB::table('permissions')
            ->where('slug', $method)
            ->where('module', $module)
            ->whereNull('deleted_at')
            ->exists();

        if (!$exists) {
            DB::table('permissions')->insert([
                'name' => $name,
                'slug' => $method,
                'module' => $module,
                'description' => $name,
                'created_at' => time(),
                'updated_at' => time()
            ]);

            $this->info("已添加权限：{$name} ({$module}.{$method})");
        }
    }

    /**
     * 生成默认权限名称
     */
    protected function generatePermissionName(string $method): string
    {
        $methodMap = [
            'list' => '列表',
            'view' => '详情',
            'create' => '创建',
            'update' => '更新',
            'delete' => '删除',
        ];

        return $methodMap[$method] ?? $method;
    }
}
